package okhttp.itydl.com.download;

import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;

import okhttp.itydl.com.download.file.FileStorageManager;
import okhttp.itydl.com.download.file.HttpManager;
import okhttp.itydl.com.download.http.DownloadCallback;
import okhttp3.Response;

/**
 * 底层【任务】 用于向文件中写入（下载）数据
 * 多线程下载  不考虑断点续传
 * @author howard
 */
public class DownloadRunnable implements Runnable {

    private long start;
    private long end;
    private String url;
    private DownloadCallback downloadCallback;

    public DownloadRunnable(long start, long end, String url, DownloadCallback downloadCallback) {
        this.start = start;
        this.end = end;
        this.url = url;
        this.downloadCallback = downloadCallback;
    }

    @Override
    public void run() {
        // 任务
        Response response = HttpManager.getInstance().syncRangeRequest(url, start, end);
        if (response == null && downloadCallback != null) {
            downloadCallback.fail(HttpManager.NETWORK_ERROR_CODE, "网络出问题了");
            return;
        }

        File file = FileStorageManager.getInstance().getFileByName(url);
        try {
            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
            // 设置文件写入位置
            raf.seek(start);
            InputStream inputStream = response.body().byteStream();
            byte[] buffer = new byte[1024 * 500];
            int len = -1;
            while ((len = inputStream.read(buffer)) != -1) {
                raf.write(buffer, 0, len);
            }
            downloadCallback.success(file);
            raf.close();
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
